package com.csi.sai.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.csi.sai.bl.dataview.GetDataView;
import com.csi.sai.bl.dataview.GetDataViewFactory;
import com.csi.sai.bl.recruitment.RecruitmentProcess;
import com.csi.sai.data.entities.Candidato;
import com.csi.sai.data.entities.Vacancy;
import com.csi.sai.utilities.Constants;
import com.csi.sai.utilities.GenericEntitie;
import com.csi.sai.utilities.Utilities;

/**
 * Servlet implementation class RecruitmentServlet
 * @param <T>
 */
@WebServlet("/web/RecruitmentServlet")
public class RecruitmentServlet<T> extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private InitialContext envContext;
	private DataSource ds;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RecruitmentServlet() {
        super();
        try {
			envContext = new InitialContext();
			Context initContext = (Context) envContext.lookup("java:/comp/env");
			ds = (DataSource) initContext.lookup("SAIDB");
			System.out.println("Data source obteined");
		} catch (NamingException e) {
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject jsonResponse = new JSONObject();
		JSONObject jsonRequest = JSONObject.fromObject(request.getParameter("jsonReq"));
		RecruitmentProcess recruitmentProcess = new RecruitmentProcess(ds);
		boolean succesfully = false;
		String process = jsonRequest.getString("process");
		if(process.equals(Constants.PROCESS_CREATEVACANCY)) {
			int type = Integer.parseInt(jsonRequest.getString("type"));
			int idDemand = jsonRequest.getString("idSolicitud").equals("") 	? 0  : Integer.parseInt(jsonRequest.getString("idSolicitud"));
			String finishDate = jsonRequest.getString("fCierre").equals("") ? "" : jsonRequest.getString("fCierre");
			String vacantesREstantes = jsonRequest.getString("vRestantes");
			succesfully = recruitmentProcess.createVacancy(type,idDemand,finishDate, vacantesREstantes);
			if(succesfully){
				jsonResponse.put("Flag", "true");
				jsonResponse.put("Folio", recruitmentProcess.getFolio());
				jsonResponse.put("vacancyID", recruitmentProcess.getIdVacancy());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if (process.equals(Constants.PROCESS_CREATECANDIDATE)) {
			int type = Integer.parseInt(jsonRequest.getString("type"));
			Candidato candidato = getCandidateFromJSONRequest(jsonRequest);
			candidato.setIdEmpleado(Utilities.getUserFromSession(request));
			succesfully = recruitmentProcess.createCandidate(type, candidato);
			if(succesfully){
				jsonResponse.put("Flag", "true");
				jsonResponse.put("idGenerated", recruitmentProcess.getIdGenerated());
				jsonResponse.put("HTMLCode", recruitmentProcess.getHTMLGenerated());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_GETCANDIDATEby)) {
			int type = Integer.parseInt(jsonRequest.getString("type"));
			Candidato c = getCandidateFromJSONRequest(jsonRequest);
			GetDataView dataView = GetDataViewFactory.getDataView(type, ds);
			succesfully = dataView.createReportBy(2, c);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", dataView.getCodeGenerated());
				jsonResponse.put("candidate", dataView.getCandidate());
			} else {
				jsonRequest.put("Flag", "false");
				jsonRequest.put("Error", "No pudo ser obtenido el reporte de Candidatos");
			}
		} else if(process.equals(Constants.PROCESS_GETVACANCYby)) {
			int type = 3;
			int idSol = 	jsonRequest.getString("idSol").equals("null") 	? 0  : Integer.parseInt(jsonRequest.getString("idSol"));
			String folio = 	jsonRequest.getString("folio").equals("null") 	? "" : jsonRequest.getString("folio");
			String dCrea = 	jsonRequest.getString("creacion").equals("null")? "" : jsonRequest.getString("creacion");
			String sts = 	jsonRequest.getString("status").equals("null") 	? "" : jsonRequest.getString("status");
			GetDataView dataview = GetDataViewFactory.getDataView(4, ds);
			succesfully = dataview.createReportVacancyBy(type, idSol, folio, dCrea, sts);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", dataview.getHTMLCode());
				jsonResponse.put("There", dataview.getThereResults());
			} else {
				jsonResponse.put("Flag", "false");
				jsonResponse.put("Error", "Error al obtener el reporte de Vacantes");
			}
		} else if(process.equals(Constants.PROCESS_GETVACTraicing)) {
			int idVacancy = Integer.parseInt(jsonRequest.getString("idVcy"));
			succesfully = recruitmentProcess.getVacancyTraicing(4,idVacancy);
			/***/
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				getVacancyValues(jsonResponse, recruitmentProcess.getVacancy());
				jsonResponse.put("HTMLCodeCandidates", recruitmentProcess.getHTMLCodeTraicing());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_CREATERELVC)) {
			int idVacancy = Integer.parseInt(jsonRequest.getString("vacancy"));
			JSONArray foundCands = jsonRequest.getJSONArray("found");
			JSONArray interCands = jsonRequest.getJSONArray("inter");
			JSONArray postCands  = jsonRequest.getJSONArray("post");
			JSONArray commsCands = jsonRequest.getJSONArray("cmnt");
			int sessionUserID = Integer.parseInt(request.getSession().getAttribute(Constants.SESSION_IDUSER).toString());
			succesfully = recruitmentProcess.createRelationshipCandVac(idVacancy, getDataFromJSONArrays(foundCands, interCands, postCands, commsCands), sessionUserID);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_ACCEPTDEMAND)) {
			int demandToUpdate = jsonRequest.getInt("idDemand");
			int idEmpleado = Utilities.getUserFromSession(request);
			succesfully = recruitmentProcess.acceptDemand(3, demandToUpdate, idEmpleado);
			if(succesfully){
				jsonResponse.put("Flag", "true");
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_DENYDEMAND)) {
			int demandToDeny = jsonRequest.getInt("idDemand");
			String comment = jsonRequest.getString("comment");
			int idEmpleado = Utilities.getUserFromSession(request);
			succesfully = recruitmentProcess.denyDemand(3, comment, demandToDeny, idEmpleado);
			if(succesfully){
				jsonResponse.put("Flag", "true");
			} else {
				jsonResponse.put("Flag", "false");
			}
		}
		
		sendResponse(response, jsonResponse);
	}

	private Candidato getCandidateFromJSONRequest(JSONObject jsonRequest) {
		Candidato c = new Candidato();
		c.setNombreCandidato(jsonRequest.getString("name"));
		c.setApellidoPaterno(jsonRequest.getString("ap"));
		c.setApellidoMaterno(jsonRequest.getString("am"));
		c.setFuente(jsonRequest.getString("cf"));
		c.setSkill(jsonRequest.getString("cs"));
		c.setCurriculum(jsonRequest.getString("cv"));
		
		c.setCorreo(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("mail")));
		c.setTelefono(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("telefono")));
		c.setTecnologia(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("tech")));
		
		c.setIdCandidate(jsonRequest.getInt("id"));
		c.setFechaAlta(jsonRequest.getString("cc"));
		c.setEstatus(jsonRequest.getString("st"));
		return c;
	}

	private GenericEntitie<T> getDataFromJSONArrays(JSONArray foundCands,
			JSONArray interCands, JSONArray postCands, JSONArray commsCands) {
		ArrayList<String> foundlist = new ArrayList<>();
		ArrayList<String> interlist = new ArrayList<>();
		ArrayList<String> postlist = new ArrayList<>();
		ArrayList<String> commslist = new ArrayList<>();
		for(int index=0;index<foundCands.size();index++) {
			JSONObject jsonObject = foundCands.getJSONObject(index);
			foundlist.add(jsonObject.getString("candidate"));
		}
		for(int index=0;index<interCands.size();index++) {
			JSONObject jsonObject = interCands.getJSONObject(index);
			interlist.add(jsonObject.getString("candidate"));
		}
		for(int index=0;index<postCands.size();index++) {
			JSONObject jsonObject = postCands.getJSONObject(index);
			postlist.add(jsonObject.getString("candidate"));
		}
		for(int index=0;index<commsCands.size();index++) {
			JSONObject jsonObject = commsCands.getJSONObject(index);
			commslist.add(jsonObject.getString("comment"));
		}
		
		GenericEntitie<T> objFoundCands = new GenericEntitie<>();
		objFoundCands.getgObjectList().add((T) foundlist);
		objFoundCands.getgObjectList().add((T) interlist);
		objFoundCands.getgObjectList().add((T) postlist);
		objFoundCands.getgObjectList().add((T) commslist);
		
		return objFoundCands;
	}

	private void getVacancyValues(JSONObject jsonResponse, Vacancy vacancy) {
		jsonResponse.put("idDemand", vacancy.getIdDemand());
		jsonResponse.put("Folio", vacancy.getFolio());
		jsonResponse.put("Status", vacancy.getEstatus());
		jsonResponse.put("Client", vacancy.getClientName());
		jsonResponse.put("Salesperson", vacancy.getSalesPerson());
		jsonResponse.put("Contact", vacancy.getContact());
		jsonResponse.put("Vacancy", vacancy.getVacancy());
		jsonResponse.put("Profile", vacancy.getProfile());
		jsonResponse.put("Creation", vacancy.getDateCreation());
		jsonResponse.put("Priority", vacancy.getPriorityDate());
		jsonResponse.put("Duration", vacancy.getDuration());
		jsonResponse.put("Rate", vacancy.getMensualRate());
		jsonResponse.put("Finish", vacancy.getFinshDate());
		jsonResponse.put("Days", vacancy.getProcessDays());
	}

	public void sendResponse(HttpServletResponse response, JSONObject jsonResponse) throws IOException {
		response.setContentType("text/xml; charset=iso-8859-1");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(jsonResponse);
	}
}
